#include <QApplication>

#include <QPixmap>
#include <QFile>
#include <QFileDialog>
#include <QFileInfo>
#include <QDebug>

bool fixPng(const QString& fileNameIn, const QString& fileNameOut);

void getAllPng(QString path, QStringList& pngList);

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QString dirPath = QFileDialog::getExistingDirectory(nullptr, "选择目录", "");
    if(!dirPath.isEmpty()) {
        QStringList pngList;
        getAllPng(dirPath, pngList);
//        qDebug() << pngList;

        foreach(QString filePath, pngList) {
            bool ret = fixPng(filePath, filePath);
            qDebug() << QString("[%1] fix [%2]")
                        .arg(ret ? "ok" : "failed")
                        .arg(filePath);
        }
        qDebug("fix end.");
    } else {
        qDebug("Please select a directory.");
    }

    return a.exec();
}


bool fixPng(const QString& fileNameIn, const QString& fileNameOut)
{
    bool ret = true;
    QPixmap pixmap;
    pixmap.load(fileNameIn);

    QFile file(fileNameOut);
    file.open(QIODevice::WriteOnly);
    ret = pixmap.save(&file, "PNG");
    file.close();
    return ret;
}


void getAllPng(QString path, QStringList& pngList)
{
    QDir dir(path);
    if (!dir.exists()) {
        return;
    }

    dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
    dir.setSorting(QDir::DirsFirst);

    foreach (QFileInfo fileInfo, dir.entryInfoList()) {
        if(fileInfo.isDir()) {
//            qDebug() << "递归目录" << fileInfo.filePath();
            getAllPng(fileInfo.filePath(), pngList);
        }
        else if(fileInfo.suffix().toLower() == "png"){
            pngList.append(fileInfo.filePath());
        }
    }
}

